$(function(){
	$(".synonym_box").keyup(function () {
		var keycode = event.which;
		 if (keycode == 32) {
			 merge(this); 
			 return false;
		 }
	});
});

//显示元素同义词输入框框
function addSynonym(obj){
	$(obj).next().next().show();
	$(obj).hide();
}

//更新元素同义词字段
function changeSynonym(obj){
	
	var param = { "synonym" : $(obj).val(), "id" : $(obj).attr("id") }
	API.dyadChangeSynonym(param, function(res) {
		if(res.code == 0) {
			window.location.reload();

		} else {
			UTIL.releaseButton(obj);
			window.location.reload();
			alert(res.desc);
		}
	});
}
function updateSynonym(obj){
	$(obj).next().show();
	$(obj).hide();
}

// 全选、取消全选的事件
function selectAll(isTest){
	var flag = false;
	if ($("#box_all").prop("checked")) {
		flag = true;
	}
	$(".id_box").each(function() {
		if(($(this).prop("checked") && !flag) || (!$(this).prop("checked") && flag)) {
			$(this).prop("checked", flag);
			preCheck(this, isTest);
		}
	});
}

// 子复选框的事件
function preCheck(obj, isTest,type){
	//当没有选中某个子复选框时，SelectAll取消选中
	var chsub = $(".id_box").length; //获取subcheck的个数
	var checkedsub = $(".id_box:checked").length; //获取选中的subcheck的个数
	if (checkedsub == chsub) {
		$("#box_all").prop("checked", true);
	} else {
		$("#box_all").prop("checked", false);
	}
	
	// 调用脚本设置预判标志
	var preFlag = "1";
	if($(obj).prop("checked")) {
		preFlag = "0";
	}
	var id = $(obj).val();
	var param = { "preFlag" : preFlag, "id" : id, "isTest" : isTest ,"type":type};
	API.dyadStdPreCheck(param, function(res) {
		if(res.code == 0) {
            // 如果是o+de勾选为正确，则带走所有的de，若错误，不带走de
			if(type == 'o+de'){
				if(preFlag == "0"){
                    $(obj).parent().next().children(".combine-s-box").each(function(){
                        $(this).prop("checked",true);
                    });
                }else {
                    $(obj).parent().next().children(".combine-s-box").each(function(){
                        $(this).prop("checked",false);
                    });
				}
			}
		} else {
			UTIL.releaseButton(obj);
			alert(res.desc);
		}
	});
}

// 分词标注问题标志
function labelCheck(obj) {

	var labelFlag = "0";
	if($(obj).prop("checked")) {
		labelFlag = "1";
	}
	var id = $(obj).val();
	var param = { "labelFlag" : labelFlag, "id" : id }
	API.dyadStdLabelCheck(param, function(res) {
		if(res.code == 0) {
			
		} else {
			UTIL.releaseButton(obj);
			alert(res.desc);
		}
	});
}

// 合并标志
function mergeCheck(obj) {

	var mergeFlag = "0";
	if($(obj).prop("checked")) {
		mergeFlag = "1";
	}
	var id = $(obj).val();
	var param = { "mergeFlag" : mergeFlag, "id" : id }
	API.dyadStdMergeElement(param, function(res) {
		if(res.code == 0) {
			
		} else {
			UTIL.releaseButton(obj);
			alert(res.desc);
		}
	});
}

// 是否展现标志
function displayCheck(obj) {

	var displayFlag = "0";
	if($(obj).prop("checked")) {
		displayFlag = "1";
	}
	var id = $(obj).val();
	var param = { "displayFlag" : displayFlag, "id" : id }
	API.dyadStdDisplayCheck(param, function(res) {
		if(res.code == 0) {
			
		} else {
			UTIL.releaseButton(obj);
			alert(res.desc);
		}
	});
}

//是否替换标志
function replaceCheck(obj) {

	var replaceFlag = "0";
	if($(obj).prop("checked")) {
		replaceFlag = "1";
	}
	var id = $(obj).val();
	var param = { "replaceFlag" : replaceFlag, "id" : id }
	API.dyadStdReplaceCheck(param, function(res) {
		if(res.code == 0) {
			
		} else {
			UTIL.releaseButton(obj);
			alert(res.desc);
		}
	});
}

/**
 * 提交本页：将本页的remove数据进行提交，包含id、是否remove标志、结果分词、结果分词属性等字段
 */
function submitPage(obj, isTest) {
	if(UTIL.checkButton(obj)) {
		// 将勾选和未勾选的id拼凑成字符串
		var checkedIds = "";
		var unCheckedIds = "";
		$(".id_box").each(function() {
			if($(this).prop("checked")) {
				checkedIds += $(this).val() + ",";
			} else {
				unCheckedIds += $(this).val() + ",";
			}
		});
		
		if(checkedIds) {
			checkedIds = checkedIds.substring(0, checkedIds.length-1);
		}
		if(unCheckedIds) {
			unCheckedIds = unCheckedIds.substring(0, unCheckedIds.length-1);
		}
		
		// 调用后台接口维护
		var param = 
		{
			"checkedIds" : checkedIds, 
			"unCheckedIds" : unCheckedIds
		};
		if(isTest) {
			// 实习生测试数据需要用该接口
			API.dyadStdCheckPageTest(param, function(res) {
				if(res.code == 0) {
					if(res.desc != '') {
						alert(res.desc);
					}
					window.location.reload();
				} else {
					UTIL.releaseButton(obj);
					alert(res.desc);
				}
			});
		} else {
			API.dyadStdCheckPage(param, function(res) {
				if(res.code == 0) {
					window.location.reload();
				} else {
					UTIL.releaseButton(obj);
					alert(res.desc);
				}
			});
		}
	}
}

/**
 * 单条提交
 */
function submitOne(obj, id) {
	if(UTIL.checkButton(obj)) {
		var checkedIds = "";
		var unCheckedIds = "";
		if($(obj).parents("tr").find(".id_box").prop("checked")) {
			checkedIds += id + ",";
		} else {
			unCheckedIds += id + ",";
		}
		
		if(checkedIds) {
			checkedIds = checkedIds.substring(0, checkedIds.length-1);
		}
		if(unCheckedIds) {
			unCheckedIds = unCheckedIds.substring(0, unCheckedIds.length-1);
		}
		
		// 调用后台接口维护
		var param = 
		{
			"checkedIds" : checkedIds, 
			"unCheckedIds" : unCheckedIds
		};
		API.dyadStdCheckPage(param, function(res) {
			if(res.code == 0) {
				window.location.reload();
			} else {
				UTIL.releaseButton(obj);
				alert(res.desc);
			}
		});
	}
}

/**
 * 切换标签上的类型
 */
function typeKeyChange(typeKey,labelFlag,disPlayFlag,mergeFlag,replaceFlag) {
	window.location.href = "dyad_std_list.htm?typeKey=" + encodeURIComponent(typeKey)+"&disPlayFlag=" +disPlayFlag + "&replaceFlag=" +replaceFlag +"&mergeFlag="+mergeFlag +"&labelFlag="+labelFlag;
}

/**
 * 更改标准词
 */
function changeStd(obj, id, dyad, isTest) {
	var _obj = $(obj);
	var std = _obj.parents("tr").find(".array").html();
	if(dyad != std) {
		var param = 
		{
			"id" : id, 
			"dyad" : dyad,
			"isTest": isTest
		};
		API.dyadChangeStd(param, function(res) {
			if(res.code == 0) {
				window.location.reload();
			} else {
				UTIL.releaseButton(obj);
				alert(res.desc);
			}
		});
	}
}

/**
 * 删除同义词
 */
function deleteSynonym(obj, dyad) {
	var _obj = $(obj);
	var std = _obj.parents("tr").find(".array").html();
	if(dyad == std) {
		alert("该词为标准词，不能删除！");
	} else {
		var param = 
		{
			"dyad" : dyad
		};
		API.dyadDeleteSynonym(param, function(res) {
			if(res.code == 0) {
				window.location.reload();
			} else {
				UTIL.releaseButton(obj);
				alert(res.desc);
			}
		});
	}
}

/**
 * 合并同义词
 */
function merge(obj) {
	if(UTIL.checkButton(obj)) {
		// 将勾选和未勾选的id拼凑成字符串
		var ids = "";
		$(".synonym_box").each(function() {
			if($(this).prop("checked")) {
				ids += $(this).val() + ",";
			}
		});
		
		if(ids) {
			ids = ids.substring(0, ids.length-1);
		}
		
		// 调用后台接口维护
		var param = 
		{
			"ids" : ids, 
		};
		API.dyadStdMerge(param, function(res) {
			if(res.code == 0) {
				window.location.reload();
			} else {
				UTIL.releaseButton(obj);
				alert(res.desc);
			}
		});
	}
}

function removeDyad(obj) {
	if($(obj).parents("tr").next().is(":hidden")) {
		$(obj).parents("tr").next().show();
	} else { // 如果是打开了分割列，则再点击按钮就把分割列关闭
		$(obj).parents("tr").next().hide();
	}
}

function updateResult(obj) {
	var _obj = $(obj);
	var boxes = _obj.parent().find(".remove-split-box");
	var vocabularys = _obj.parent().find(".remove-split-vocabulary");
	var properties = _obj.parent().find(".remove-split-property");
	
	var checked = _obj.parent().find(".remove-split-box:checked");
	if(checked.length == 0) {
		_obj.prop("checked", true);
		alert("不能把分词全部取消！");
		return;
	}
	
	var array = ',', partPattern = ',';
	for(var i=0;i<boxes.length;i++) {
		if($(boxes[i]).prop("checked")) {
			array += $(vocabularys[i]).html() + ",";
			partPattern += $(properties[i]).val() + ",";
		}
	}
	
	_obj.parents("td").next().find(".result-array-span").html(array);
	_obj.parents("td").next().find(".result-pattern-span").html(partPattern);
	_obj.parents("td").next().find(".result-array-input").val(array);
	_obj.parents("td").next().find(".result-pattern-input").val(partPattern);
}

function addRemove(obj) {
	if(UTIL.checkButton(obj)) {
		// 校验o的数量是否正确
		var errorMsg1 = "";
		if($("#typeKey").val()=="o+oa" || $("#typeKey").val()=="o+s") {
			var resultPattern = $(obj).parent().find("input[name='resultPattern']").val();
			if(resultPattern && (resultPattern.split("o,").length - 1) != 1) {
				errorMsg1 += $(obj).parents("tr").prev().find(".array span").html();
			}
		}
		// 校验s的数量是否正确
		var errorMsg2 = "";
		if($("#typeKey").val()=="o+s") {
			var resultPattern = $(obj).parent().find("input[name='resultPattern']").val();
			if(resultPattern && (resultPattern.split("s").length - 1) != 1) {
				errorMsg2 +=$(obj).parents("tr").prev().find(".array span").html();
			}
		}
		
		// 综合错误信息
		var errorMsg = "";
		if(errorMsg1) {
			errorMsg += "remove后的词语中属性o应该有且只有一个;";
			errorMsg += "\n";
		}
		if(errorMsg2) {
			errorMsg += "remove后的词语中属性s应该有且只有一个;";
			errorMsg += "\n";
		}
		if(errorMsg) {
			UTIL.releaseButton(obj);
			alert(errorMsg);
			return false;
		}
		
		// 调用后台接口维护
		var formData = $(obj).parents('form').serialize();
		API.dyadStdAddRemove(formData, function(res) {
			if(res.code == 0) {
				window.location.reload();
			} else {
				if(res.code == 30001) {
					if(confirm(res.desc)) {
						formData += "&confirmFlag=1";
						API.dyadStdAddRemove(formData, function(res) {
							if(res.code == 0) {
								window.location.reload();
							} else {
								alert(res.desc);
							}
						});
					}
					UTIL.releaseButton(obj);
				} else {
					UTIL.releaseButton(obj);
					alert(res.desc);
				}
			}
		});
	}
}

function submitBaseDyad(obj) {

	if(UTIL.checkButton(obj)) {
		if(confirm("是否确认提交？")) {
			// 将按钮改变成提交中状态
			$(obj).val("提交中");
			$(obj).removeClass("button");
			
			API.dyadStdSubmitBase(function(res) {
				if(res.code == 0) {
					alert("提交成功！");
				} else {
					alert(res.desc);
				}
				$(obj).val("完成提交");
				$(obj).addClass("button");
				UTIL.releaseButton(obj);
			});
		} else {
			UTIL.releaseButton(obj);
		}
	}

}

function changeCountPerPage(obj) {
	var countPerPage = $(obj).val();
    var g = /^[1-9]*[1-9][0-9]*$/;
	if(g.test(countPerPage)) {
		window.location.href = "dyad_std_list.htm?countPerPage=" + countPerPage;
	}
}

function updateCombineS(obj, id,type) {
	var combineS = ',';
	$(obj).parent().find(".combine-s-box").each(function() {
		if ($(this).prop("checked")) {
			combineS += "1,";
		} else {
			combineS += "0,";
		}
	});

	var param = { "combineS" : combineS, "id" : id,"type":type };
	API.dyadStdUpdateCombineS(param, function(res) {
		if(res.code == 0) {
			if('o+de'==type){
                //如果是o+de需要判断是否所有的de都被带走~只要有没带走的de就是错误的
                API.dyadStdUpdateODeFlag(param, function(res) {
                    if(res.code == 0) {
						if(res.desc == '0'){
							$(obj).parent().prev().children("#preFlag").prop("checked",false);
						}else{
                            $(obj).parent().prev().children("#preFlag").prop("checked",true);
                        }
                    } else {
                        alert(res.desc);
                    }
                });

            }

		} else {
			alert(res.desc);
		}
	});
}

function changeSentenceOrder(id, so) {

	var param = { "sentenceOrder" : so, "id" : id }
	API.dyadStdUpdateSentenceOrder(param, function(res) {
		if(res.code == 0) {
			window.location.reload()
		}
	});
}


function changeKeyRelation2(obj){
	if($(obj).html().trim()=='and'){
		$(obj).html('or');
	}else{
		$(obj).html('and');
	}
}

function addOInput(obj,keyType){
	var oNum = $('#oNum').val();
	var content = "";
	if(oNum < 8){
		if(oNum == 2){
			$("#oDiv").attr("style","display:block;");
		}
		content += '<span onclick="changeKeyRelation2(this);" class="word-border"  style="border-color: #b77777;" id = "okey'+ oNum +'">and</span>';
		if(keyType.indexOf('o')>-1){
			content += '<label >o小词</label>';
		}else{
			content += '<label >标准词</label>';
		}
		var num = ++oNum;
		content += '<input type="text" class="small-field" onkeyup="searchEnter(event,\''+keyType +'\');" id="oArray'+ num +'" name="oArray'+ num +'">';
		$('#oDiv').append(content);
		$('#oNum').val(oNum);
	}
}

function addSInput(obj,keyType){
	var sNum = $('#sNum').val();
	if(sNum < 6){
		var content = '';
		var num = ++sNum;
		sNum--;
		content += '<span onclick="changeKeyRelation2(this);" class="word-border" style="border-color: #b77777;" id = "skey'+ num +'">and</span>';
		content += '<label >s小词</label>';
		content += '<input type="text" class="small-field" onkeyup="searchEnter(event,\''+keyType +'\');" id="sArray'+ num +'" name="sArray'+ num +'">';
		$('#sDiv').append(content);
		$('#sNum').val(num);
		sNum ++;
	}
}

function submitSearch(keyType){
	var sNum1 = $('#sNum').val();
	var oNum1 = $('#oNum').val();

	var oWord = '';
	var oKey = '';
	oWord += $("#arrayKey").val()==undefined ? '':$("#arrayKey").val().trim();
	oWord += '|';
	oWord += $("#arrayKey2").val()==undefined ? '':$("#arrayKey2").val().trim();
	oKey += $("#keysRelation").val()==undefined ? '':$("#keysRelation").val().trim();
	for(var i = 3; i <= oNum1;i++){
		oWord += '|';
		oWord += $("#oArray"+i).val()==undefined ? '':$("#oArray"+i).val().trim();
		oKey += '|';
		oKey += $("#okey"+(i-1)).html()==undefined ? '':$("#okey"+(i-1)).html().trim();
	}
	var sWord = '';
	var sKey = '';
	if(keyType.indexOf('s')>-1 && keyType != 'si+de'){
		for(var i = 1;i<=sNum1; i++){
			if(i==1){
				sWord += $("#sArray"+i).val()==undefined ? '':$("#sArray"+i).val().trim();
				sKey += $("#skey"+i).html()==undefined ? '':$("#skey"+i).html().trim();
			}else{
				sWord += '|';
				sWord += $("#sArray"+i).val()==undefined ? '':$("#sArray"+i).val().trim();
				sKey += '|';
				sKey += $("#skey"+i).html()==undefined ? '':$("#skey"+i).html().trim();
			}
		}
	}
	
	var param = 
	{
		"arrayKey3" : $("#arrayKey3").val()==undefined ? '':$("#arrayKey3").val().trim(),
		"exactSearchFlag" : $("#exactSearchFlag").val().trim(),
		"sWord" : sWord,
		"oWord" : oWord,
		"oKey" : oKey,
		"sKey" : sKey,
	};
	var arrayKey3 = $("#arrayKey3").val()==undefined ? '':$("#arrayKey3").val().trim();
	var content = "dyad_std_list.htm?arrayKey3=" + arrayKey3 +"&exactSearchFlag="+$("#exactSearchFlag").val().trim()+"&sWord="+encodeURIComponent(sWord)+"&oWord="+encodeURIComponent(oWord)+"&oKey="+encodeURIComponent(oKey)+"&sKey="+encodeURIComponent(sKey) ;
	window.location.href = content;
		
}

function searchEnter(event,keyType) {
    event = event || window.event;
    if (event.keyCode == 13) {
    	submitSearch(keyType);
    }
}

function mergeTrueDyadByElementStd(obj) {
	if(UTIL.checkButton(obj)) {
		if(confirm("是否确认合并？")) {
			// 将按钮改变成提交中状态
			$(obj).val("合并中");
			$(obj).removeClass("button");
			
			API.mergeTrueDyadByElementStd(function(res) {
				if(res.code == 0) {
					alert("合并成功！");
					window.location.reload();
				} else {
					alert(res.desc);
				}
				$(obj).val("合并同义词");
				$(obj).addClass("button");
				UTIL.releaseButton(obj);
			});
		} else {
			UTIL.releaseButton(obj);
		}
	}
}

